package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.date.LocalDateTimeUtil;
import ch.qos.logback.core.net.server.Client;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.DeviceShadowData;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceShadowRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceShadowResponse;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.serve.domain.*;
import com.zzyl.serve.dto.FamilyMemberRequestDto;
import com.zzyl.serve.domain.DeviceData;
import com.zzyl.serve.domain.Elder;
import com.zzyl.serve.dto.UserLoginRequestDto;
import com.zzyl.serve.mapper.DeviceDataMapper;
import com.zzyl.serve.mapper.DeviceDataMapper;
import com.zzyl.serve.mapper.ElderMapper;
import com.zzyl.serve.service.WechatService;
import com.zzyl.serve.vo.IndexDataVo;
import com.zzyl.serve.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.FamilyMemberMapper;
import com.zzyl.serve.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import static com.zzyl.common.utils.PageUtils.startPage;

/**
 * 老人家属Service业务层处理
 * 
 * @author itheima
 * @date 2025-03-12
 */
@Slf4j
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private ElderMapper elderMapper;

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }


    @Autowired
    private WechatService webschatService;

    @Autowired
    private TokenService tokenService;

    /**
     *  小程序端 用户登录的逻辑处理
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {


        //1.根据code调用微信api获取apenId
        String openid = webschatService.getOpenid(dto.getCode());

        //2.根据openId查询数据库获取用户信息family_member表
        FamilyMember familyMember = getOne(
                new LambdaQueryWrapper<FamilyMember>()
                        .eq(FamilyMember::getOpenId, openid)
        );

        //3.调用微信api获取用户绑定手机号
        String phone = webschatService.getPhone(dto.getPhoneCode());


        //4.判断用户信息是否存在，如果不存在，则新增family_member表
        //5.存在则 修改family_member表数据
        if(ObjectUtil.isNull(familyMember)){
            // 新用户


            familyMember = new FamilyMember();
            familyMember.setPhone(phone);
            familyMember.setOpenId(openid);

            // 设置初始随机名称
            familyMember.setName("花开富贵" + DateUtils.getTime());

            save(familyMember);

        }else {
            // 老用户
            familyMember.setPhone(phone);
            updateById(familyMember);
        }


        //6.将用户id存入token中，并返回数据给前端
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("nickName", familyMember.getName());

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());
        return loginVo;
    }

    @Override
    public void addFamilyMember(FamilyMemberRequestDto dto) {
        //通过老人身份证号查询老人信息
        Elder elder = familyMemberMapper.selectElderByIdCard(dto.getIdCard());
        log.info("elder:{}", elder);
        if (ObjectUtil.isNull(elder)) {
            throw new RuntimeException("该老人不存在");
        }
        //将称呼保存到remark字段中
        String remark = dto.getRemark();
//将老人家属id和老人id保存到family_member_elder表中
//获取当前登录人的id
        Long familyMemberId = UserThreadLocal.getUserId();
        int i = familyMemberMapper.insertFamilyMemberElder(familyMemberId, elder.getId());
        log.info("增加:{}", i);
        familyMemberMapper.updateElder(remark, elder.getId());


    }

    //分页查询老人列表
    @Override
    public List<ElderInfo> listByPage(String pageNum, String pageSize) {
        startPage();
        //获取用户ID
        Long userId = UserThreadLocal.get();
        List<ElderInfo> info = familyMemberMapper.listByPage(pageNum, pageSize, userId);
        //info.setMid(userId);
        info.forEach(e -> {
            e.setMid(userId);
        });
        return info;
    }
    /**
     * 1.6 按周统计查询指标数据
     * */
    @Override
    public IndexDataVo queryDeviceDataListByWeek() {
        IndexDataVo vo = new IndexDataVo();
        List<Map<String, Object>> list = new ArrayList<>();
        // 根据登录的家属id找到老人,得到老人id
        List<Elder> elderList = elderMapper.getElderByFamilyMemberId(UserThreadLocal.getUserId());
        if(ObjectUtil.isEmpty(elderList)){
            return null;
        }
        for (Elder elder : elderList) {
            String elderName = elder.getName();
            // 查询设备数据列表
            List<DeviceData> deviceDataList = deviceDataMapper.queryDeviceDataListByWeek(elderName);

            // 判断设备数据列表是否为空或包含 null
            if (ObjectUtil.isNotEmpty(deviceDataList)) {
                for (DeviceData deviceData : deviceDataList) {
                    // 对 deviceData 非空校验
                    if (deviceData != null && deviceData.getAlarmTime() != null) {
                        LocalDateTime alarmTime = deviceData.getAlarmTime();
                        Map<String, Object> map = new HashMap<>();
                        // 创建一个DateTimeFormatter实例，指定模式为"MM.dd"
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM.dd");
                        // 使用formatter格式化alarmTime
                        String dateTime = alarmTime.format(formatter);
                        int dataValue = Integer.parseInt(deviceData.getDataValue());
                        map.put("dateTime", dateTime);
                        map.put("dataValue", dataValue);
                        list.add(map);
                    }
                }
            }
        }

        vo.setCode(200);
        vo.setMsg("操作成功");
        vo.setData(list);
        vo.setOperationTime(null);

        return vo;
    }
    @Override
    public IndexDataVo queryDeviceDataListByDay(String functionId, Long startTime, Long endTime, String iotId) {
//        转换时间格式
        LocalDateTime start = LocalDateTimeUtil.of(startTime);
        LocalDateTime end  = LocalDateTimeUtil.of(endTime);
        List<Map<String, Object>> maps = deviceDataMapper.queryDeviceDataListByDay(functionId, start, end, iotId);
        IndexDataVo indexDataVo = new IndexDataVo();
        indexDataVo.setData(maps);
        indexDataVo.setCode(200);
        indexDataVo.setMsg("查询成功");

        return indexDataVo;

    }
    /**
     * 1.5 按天统计查询指标数据
     * */

    @Override
    public List<Elder> selectMyFamilyMemberList() {

        //根据openId查询用户的id
        Long familyMemberId = UserThreadLocal.getUserId();
        if (ObjectUtil.isNull(familyMemberId)) {
            throw new RuntimeException("用户不存在");
        }
        //查询老人id
        List<Long> elderIdList = familyMemberMapper.selectElderIdByFamilyMemberId(familyMemberId);
        //根据老人ID查询老人信息
        List<Elder> elderList = new ArrayList<>();
        if (CollUtil.isNotEmpty(elderIdList)) {
            //遍历老人ID集合，查询老人信息
            elderIdList.forEach(elderId -> {
                log.info("elderId:{}", elderId);
                Elder elder = familyMemberMapper.selectById(elderId);
                elderList.add(elder);
            });
        }
        return elderList;

    }
    //1.4获得老人数据
    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if(CollUtil.isEmpty(shadow)){
            List<Object> emptyList = Collections.emptyList();
            return AjaxResult.success(emptyList);
        }
        //返回数据
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        List<Map<String,Object>> list = new ArrayList<>();

        //处理上报时间日期
        LocalDateTime activeTime =  LocalDateTimeUtil.parse(
                shadow.get(0).getReported().getEventTime(),
                "yyyyMMdd'T'HHmmss'Z'"
        );
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k,v)->{
            Map<String,Object> map = new HashMap<>();
            map.put("functionId",k);
            map.put("value",v);
            map.put("eventTime",eventTime);
            list.add(map);
        });

        return AjaxResult.success(list);
    }



}
